<?php
namespace App\Goods\Http\Controllers;

use App\ApiBaseController;
use App\Exceptions\GoodsException;
use App\Goods\Services\GoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GoodsController extends ApiBaseController
{
    /**
     * 表单验证
     * @param $data
     * @param $type
     * @return bool
     * @throws GoodsException
     */
    protected function validate($data, $type)
    {
        $rule = [];
        $message = [];
        switch ($type){
            case 'create':
                $rule = [
                    'base_id' => 'required',
                    'type_one' => 'required',
                    'type_two' => 'required',
                    'type_three' => 'required',
                    'type_four' => 'required',
                    'common_name_id' => 'required|integer',
                    'product_name' => 'required|string',
                    'pinyin' => 'required|string',
                    'spec' => 'required|string',
                    'cert_sn' => 'required',
                    'end_date' => 'required|date',
                    'images' => 'required',
                    'title' => 'required',
                    'approve_date' => 'date'
                ];
                $message = [
                    'base_id.required' => '缺少商品基本信息ID',
                    'type_one.required' => '请先选择分类',
                    'type_two.required' => '请先选择分类',
                    'type_three.required' => '请先选择分类',
                    'type_four.required' => '请先选择分类',
                    'common_name_id.required' => '请选择通用名',
                    'product_name.required' => '请输入产品名称',
                    'pinyin.required' => '请输入拼音码',
                    'spec.required' => '请输入规格',
                    'cert_sn.required' => '请输入批件号',
                    'end_date.required' => '请选择截止日期',
                    'images.required' => '请上传产品图片',
                    'title.required' => '请输入标题',
                    'end_date.date' => '戒指日期必须为日期格式',
                    'approve_date.date' => '批准日期必须为日期格式',
                ];
                break;
        }

        $validate = Validator::make($data, $rule, $message);
        if($validate->fails()){
            throw new GoodsException($validate->errors()->first());
        }
        return true;
    }

    /**
     * 添加商品
     * @param Request $request
     */
    public function create(Request $request)
    {
        $param = $request->input();
        try {
            // 表单验证
            $this->validate($param, 'create');
            $service = new GoodsService();
            $res = $service->save($param);
            if(!$res){
                throw new GoodsException('添加失败!');
            }
            return $this->success('添加成功！');
        }catch (GoodsException $exception){
            return $this->error($exception->getMessage());
        }
    }


}
